using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class UpgradeWingman:Upgrade {

	public UpgradeWingman() {

	}

	GameObject generatedObject;
	WeaponSlot generatedWeaon;
	Mob generatedMob;
	float timeAfterGeneration = 10;
	float timeAfterAmmoGiven;

	public override void Update(object sender,WeaponEventArgs e) {

		if(weapon.owner.GetComponent<PlayerMinionController>()) return;

		base.Update(sender,e);
		Debug.Log(generatedObject);
		if(!generatedObject) {

			timeAfterGeneration+=deltaTime;
			AddProgression(timeAfterGeneration/10f);
			if(timeAfterGeneration>10) {
				DoGeneration();
				timeAfterGeneration=0;
			}
		} else {

			if(!generatedObject.activeSelf) {
				generatedObject.SetActive(true);
				generatedObject.transform.position=weapon.transform.position;
			}

			timeAfterGeneration=0;


		}
	}

	public override void OnDisable() {
		base.OnDisable();
		if(generatedObject) generatedObject.SetActive(false);
	}
	public override void OnDequip() {
		base.OnDequip();
		if(generatedObject) Object.Destroy(generatedObject);
	}
	void DoGeneration() {

		GameObject prefab = Resources.Load<GameObject>("SentientWeapon");
		generatedMob=MobManager.Create(prefab,weapon.muzzle.position);

		if(weapon.isPlayer)
			generatedMob.gameObject.AddComponent(typeof(PlayerMinionController));
		WeaponInstance newWeapon = new WeaponInstance(weapon.weaponInstance.weaponData);

		newWeapon.weaponLevel=weapon.weaponInstance.weaponLevel;
		newWeapon.baseUpgradeSlotCount=weapon.weaponInstance.baseUpgradeSlotCount;

		foreach(var i in weapon.weaponInstance.upgradeInstances) {
			if(i.upgradeData.typeName=="UpgradeWingman") continue;
			newWeapon.TryAddUpgrade(new UpgradeInstance(i.upgradeData),newWeapon.upgradeInstances.Last);
		}

		newWeapon.currentClip=new ClipStats();
		newWeapon.currentClip.clipSize=weapon.weapon.currentClip.clipSizeInt;
		newWeapon.weaponLevel=weapon.weaponInstance.weaponLevel;

		generatedMob.GetComponentInChildren<WeaponSlot>().weaponInstance=newWeapon;
		generatedMob.faction=weapon.owner.faction;
		if(generatedMob.GetComponent<DestroyAfterClipDepletion>())
			Object.Destroy(generatedMob.GetComponent<DestroyAfterClipDepletion>());

		generatedObject=generatedMob.gameObject;
		generatedWeaon=generatedMob.GetComponentInChildren<WeaponSlot>();
		var link = generatedObject.AddComponent<EnergyConsumptionLink>();
		link.targetMob=weapon.owner;
	}
}
